package com.czy.lxtFX;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpRequestUtil {
    private static final String proxyHost = "127.0.0.1";
    private static final int proxyPort = 8087;

    private static HttpURLConnection getConnection(String urlStr, String requestMethod, boolean isProxy) {
        HttpURLConnection conn;
        try {
            var url=new URL(urlStr);
            if (isProxy) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                conn = (HttpURLConnection) url.openConnection(proxy);
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.setRequestMethod(requestMethod);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return conn;
    }
    private static void setCon(HttpURLConnection conn, boolean isJsonData, String param){
        conn.setRequestProperty("Charsert", StandardCharsets.UTF_8.toString()); //设置请求编码
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        if (isJsonData){
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", param.getBytes().length+"");
            conn.setDoOutput(true);
        }
        try {
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void write(HttpURLConnection con, String param) {
        if (param==null||param.strip().equals("")){
            return;
        }
        try (var writer = new PrintWriter(new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8))) {
            writer.print(param);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static String read(HttpURLConnection con){
        try(var reader = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
            var result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    public static String sendGet(String url, boolean isJsonData, String param) {
        if (param==null||param.strip().equals("")){
            isJsonData=false;
        }
        if (!isJsonData){
            url+="?"+param;
        }
        var conn = getConnection(url, "GET", false);
        if (conn==null){
            return "";
        }
        setCon(conn,isJsonData,param);
        if (isJsonData){
            write(conn,param);
        }
        return read(conn);
    }
    /*参数二：参数是否是json格式。参数四：是否代理模式*/
    public static String sendPost(String url, boolean isJsonData, String param, boolean isProxy) {
        if (!isJsonData){
            url+="?"+param;
        }
        var conn = getConnection(url, "POST", isProxy);
        if (conn==null){
            return "";
        }
        setCon(conn,isJsonData,param);
        if (isJsonData){
            write(conn,param);
        }
        return read(conn);
    }

    public static String sendGetOld(String url, String param) {
        BufferedReader in = null;
        try {
            if (StringUtil.isNotBlank(param)) {
                url += "?" + param;
            }
            var conn = getConnection(url, "GET", false);
            if (conn==null){
                return "";
            }
            conn.connect();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
    public static void main(String[] args) {
        //demo:代理访问
        String url = "http://8.129.86.206:20111/ConsumerProofMQ_api/MachineProof";
        var par="{\"typeId\":\"6\",\"posData\":{\"typeId\":6,\"investorId\":\"140000000000000001\",\"schoolId\":\"1\",\"machineId\":\"99113006000007B7\",\"machineGroup\":0,\"deviceVer\":\"01,02\",\"siteFlag\":1,\"siteId\":\"155151146253691047\",\"studentHex\":\"00000009\",\"posPrice\":\"2233\",\"posLitre\":\"\",\"posUseSecond\":\"\",\"posDatetimeFlag\":2,\"posDatetime\":\"20201216170036\",\"cardinfoFlag\":0,\"collectionFlag\":1,\"onlineFlag\":0,\"dbUnique\":\"9911300007B7,00000009,08B9,01F6\",\"upDatetime\":\"20201216170036\"}}";
        //String para = "";
        String sr = HttpRequestUtil.sendGet(url,true, par);
        System.out.println(sr);
    }
}
